package sdk

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"

	"github.com/yourusername/virt-manager-go/internal/models"
)

// SystemClient 提供系统相关的 API 操作
type SystemClient struct {
	client *APIClient
}

// NewSystemClient 创建新的系统客户端
func NewSystemClient(client *APIClient) *SystemClient {
	return &SystemClient{
		client: client,
	}
}

// GetSystemInfo 获取系统信息
func (s *SystemClient) GetSystemInfo(ctx context.Context, connectionID string) (*models.SystemInfo, error) {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/system/info?connection=%s", url.QueryEscape(connectionID))

	data, err := s.client.Get(ctx, u)
	if err != nil {
		return nil, fmt.Errorf("failed to get system info: %w", err)
	}

	var info models.SystemInfo
	if err := json.Unmarshal(data, &info); err != nil {
		return nil, fmt.Errorf("failed to unmarshal system info: %w", err)
	}

	return &info, nil
}

// GetCapabilities 获取系统能力
func (s *SystemClient) GetCapabilities(ctx context.Context, connectionID string) (string, error) {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/system/capabilities?connection=%s", url.QueryEscape(connectionID))

	data, err := s.client.Get(ctx, u)
	if err != nil {
		return "", fmt.Errorf("failed to get capabilities: %w", err)
	}

	return string(data), nil
}

// GetVersion 获取系统版本
func (s *SystemClient) GetVersion(ctx context.Context) (map[string]interface{}, error) {
	data, err := s.client.Get(ctx, "/api/v1/version")
	if err != nil {
		return nil, fmt.Errorf("failed to get version: %w", err)
	}

	var version map[string]interface{}
	if err := json.Unmarshal(data, &version); err != nil {
		return nil, fmt.Errorf("failed to unmarshal version: %w", err)
	}

	return version, nil
}

// HealthCheck 执行健康检查
func (s *SystemClient) HealthCheck(ctx context.Context) error {
	_, err := s.client.Get(ctx, "/api/v1/health")
	if err != nil {
		return fmt.Errorf("health check failed: %w", err)
	}
	return nil
}
